﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Savage.DotNetLibrary.ProtocolLibrary
{
    public class IOWrapper
    {
        public static string RandomFileRename(string path)
        {
            string tempFileName = "";
            do
            {
                //This should in theory only run once, 
                //but this is to check that the temporary file
                //does not already exist
                tempFileName = Guid.NewGuid().ToString();
            } while (System.IO.File.Exists(System.IO.Path.GetDirectoryName(path) + @"\" + tempFileName));
            //We can now store this with the directory
            tempFileName = System.IO.Path.GetDirectoryName(path) + @"\" + tempFileName;

            //Rename the file
            System.IO.File.Move(path, tempFileName);

            return tempFileName;
        }

        public static string FileContentsToBase64Hash(string path)
        {
            //Perform a hash of the file contents
            System.IO.FileInfo fi = new System.IO.FileInfo(path);
            using (System.IO.FileStream reader = fi.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                byte[] content = new byte[fi.Length];
                reader.Read(content, 0, content.Length);

                System.Security.Cryptography.SHA1 alg = System.Security.Cryptography.SHA1.Create();
                byte[] hash = alg.ComputeHash(content);

                reader.Close();

                //now encode to Base64 the hash
                return Convert.ToBase64String(hash);
            }
        }
    }
}
